//
//  LaunchImageViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/17.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "LaunchImageViewController.h"
#import "MainViewController.h"
#import "NetworkingTool.h"
//#import "JKTopWindowViewController.h"
#import "UIImageView+WebCache.h"
//#import "JKDateTool.h"

@interface LaunchImageViewController ()
/** 版权的Label */
@property (nonatomic, weak) UILabel *sourceLabel;

/** 动画完成后跳转的控制器 */
@property (nonatomic, strong) UIViewController *viewController;

/** 目标图片View */
@property (nonatomic, weak) UIImageView *launchImageView;

/** 底部容器视图 */
@property (nonatomic, weak) UIView *bottomView;

/** 底部画图的icon */
@property (nonatomic, weak) IconView *iconView;

/** icon画完之后换成的图片 */
@property (nonatomic, weak) UIImageView *iconImgView;

/** link定时器 */
@property (nonatomic, strong) CADisplayLink *link;

/** 夜间模式遮盖view */
@property (nonatomic, weak) UIView *maskView;
@end

@implementation LaunchImageViewController

#pragma mark - 懒加载
- (UIView *)maskView{
    if (!_maskView) {
        UIView *maskView = [[UIView alloc] init];
        maskView.frame = self.view.bounds;
        maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        maskView.userInteractionEnabled = NO;
        [self.view addSubview:maskView];
        _maskView = maskView;
    }
    return _maskView;
}

//常量
static CGFloat const animationDuration = 4.0; //动画的时间
static CGFloat const scale = 1.15;            //放大倍数

#pragma mark - 生命周期方法
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.bottomView.y = JKScreenH-100;
    } completion:^(BOOL finished) {
        //定时器，使用该定时器画出icon
        CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawIcon)];
        self.link = link;
        [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    }];
    
    //开始设置动画
    [UIView animateWithDuration:animationDuration animations:^{
        CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
        self.launchImageView.transform = transform;
    }];
    
    [self performSelector:@selector(changeToMainViewController) withObject:nil afterDelay:animationDuration];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //隐藏状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    [self setup];
    
    [self loadLaunchImage];
}

- (void)setup{
    [self.view bringSubviewToFront:self.maskView];
    
    //加载图片,并加入view中
    UIImageView *launchImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view insertSubview:launchImageView atIndex:0];
    self.launchImageView = launchImageView;
    
    //初始化版权Label
    UILabel *sourceLabel = [[UILabel alloc] initWithFrame:(CGRectMake((JKScreenW-200)/2, (JKScreenH-133), 200, 30))];
    self.sourceLabel = sourceLabel;
    self.sourceLabel.font = [UIFont systemFontOfSize:12];
    self.sourceLabel.textAlignment = NSTextAlignmentCenter;
    self.sourceLabel.textColor = JKColor(237, 237, 237);
    self.sourceLabel.backgroundColor = [UIColor clearColor];
    self.sourceLabel.shadowColor = [UIColor darkGrayColor];
    self.sourceLabel.shadowOffset = CGSizeMake(1, 0);
    [self.view addSubview:self.sourceLabel];
    
    //初始化底部视图
    [self setupBottomView];
}

- (void)loadLaunchImage{
    
    NSString *imageUrl = [[NSUserDefaults standardUserDefaults] objectForKey:JKLaunchImageUrlKey];
    NSString *imageSource = [[NSUserDefaults standardUserDefaults] objectForKey:JKLaunchImageSourceKey];
    UIImage *image = nil;
    // 如果能取得缓存图及图片来源，直接返回，无需网络请求
    if (imageUrl != nil && imageSource != nil) {
        image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:imageUrl];
        if (image != nil) {
            self.launchImageView.image = image;
            self.sourceLabel.text = imageSource;
        }
    }
    
    /* 知乎日报通常每周一更新启动图片，所以判断上次启动时间与本次启动时间是否为同一周（目前看来并非如此）
    int lastLaunchDate = [[[NSUserDefaults standardUserDefaults] objectForKey:JKLastDateToLaunchKey] intValue];
    int todayDate = [JKDateTool getDateOfToday];
    //BOOL isSameWeek = [JKDateTool isDate:lastLaunchDate inTheSameWeekWithAnotherDate:todayDate];
    
    if (lastLaunchDate != todayDate) {// 避免重复赋值
        [[NSUserDefaults standardUserDefaults] setObject:@(todayDate) forKey:JKLastDateToLaunchKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }*/                                                                                                                                                                                                                                                                                                                
    
    // 进行网络请求，获取启动图片
    [[NetworkingTool sharedNetworkingTool] GET:@"http://news-at.zhihu.com/api/7/prefetch-launch-images/1242*1920" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSString *imgUrlStr = [responseObject[@"creatives"] firstObject][@"url"];
        NSString *name = [responseObject[@"creatives"] firstObject][@"text"];
        
        if ([imgUrlStr isEqualToString:imageUrl] && image != nil) return;
        
        [self.launchImageView sd_setImageWithURL:[NSURL URLWithString:imgUrlStr]];
        self.sourceLabel.text = name;
        
        if (!imgUrlStr) {
            self.launchImageView.image = [UIImage imageNamed:@"launch_img_bak.jpg"];
        }
        
        if (!name && !imgUrlStr) {
            self.sourceLabel.text = @"啊哦，启动图api又更新了";
        }
        
        [[NSUserDefaults standardUserDefaults] setObject:imgUrlStr forKey:JKLaunchImageUrlKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSUserDefaults standardUserDefaults] setObject:name forKey:JKLaunchImageSourceKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 启动页面不用进行网络提示
    }];
}

- (void)setupBottomView{
    //底部容器视图
    UIView *bottomView = [[UIView alloc] initWithFrame:(CGRectMake(0, JKScreenH, JKScreenW, 100))];
    bottomView.backgroundColor = [UIColor colorWithRed:24/255.0 green:24/255.0 blue:24/255.0 alpha:1];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    //icon图片的imageView
    UIImageView *iconImgView = [[UIImageView alloc] initWithFrame:(CGRectMake(20, (bottomView.height - 60) * 0.5, 50, 50))];
    iconImgView.image = [UIImage imageNamed:@"AD_Icon_Border"];
    [bottomView addSubview:iconImgView];
    self.iconImgView = iconImgView;
    
    // 要画出来的iconView
    IconView *iconView = [[IconView alloc] init];
    iconView.backgroundColor = [UIColor clearColor];
    iconView.frame = iconImgView.bounds;
    [iconImgView addSubview:iconView];
    self.iconView = iconView;
    
    //标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.height = 25;
    titleLabel.width = 200;
    titleLabel.x = iconImgView.x + iconImgView.width + 15;
    titleLabel.y = iconImgView.y;
    titleLabel.text = @"知乎日报";
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textColor = [UIColor colorWithRed:196/255.0 green:200/255.0 blue:208/255.0 alpha:1];
    [bottomView addSubview:titleLabel];
    
    // 子标题
    UILabel *subTitleLabel = [[UILabel alloc] init];
    subTitleLabel.height = 25;
    subTitleLabel.width = 200;
    subTitleLabel.x = titleLabel.x;
    subTitleLabel.y = CGRectGetMaxY(titleLabel.frame);
    subTitleLabel.text = @"每天三次，每次七分钟";
    subTitleLabel.backgroundColor = [UIColor clearColor];
    subTitleLabel.textAlignment = NSTextAlignmentLeft;
    subTitleLabel.font = [UIFont systemFontOfSize:14];
    subTitleLabel.textColor = [UIColor colorWithRed:99/255.0 green:102/255.0 blue:105/255.0 alpha:1];
    [bottomView addSubview:subTitleLabel];
}

- (void)drawIcon{
    
    self.iconView.progress = self.iconView.progress + 1/60.0;
    
    if (self.iconView.progress >= 1) {
        self.iconImgView.image = [UIImage imageNamed:@"AD_Icon_iOS7"];
        self.iconView.hidden = YES;
    }
    
    if (self.iconView.progress >= animationDuration) {
        
        [self changeToMainViewController];
        
        [self.link invalidate];
        self.link = nil;
    }
}

//动画显示完毕后,把页面跳转到主视图
- (void)changeToMainViewController{
    
    [self.link invalidate];
    self.link = nil;
    
    [[NetworkingTool sharedNetworkingTool].tasks makeObjectsPerformSelector:@selector(cancel)];
    [[SDWebImageManager sharedManager] cancelAll];
    
    MainViewController *mainVc = [[MainViewController alloc] init];
    mainVc.jumpTo = self.jumpTo;
    
    //跳转页面
    //本打算先将控制器modal出来，再设置为根控制器，但是这样的话，启动图片控制器无法销毁~~
    //所以直接替换根控制器
    [UIApplication sharedApplication].keyWindow.rootViewController = mainVc;
}

- (void)dealloc{
    JKLog(@"%s", __func__);
    
    [self.link invalidate];
    self.link = nil;
    
    //显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}
@end

#pragma mark - 画icon的view
@implementation IconView

- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
    
    //以下数字都是慢慢微调出来的~~
    CGFloat radius = rect.size.width > rect.size.height ? rect.size.height * 0.265 : rect.size.width * 0.265;
    CGFloat startA = M_PI_2;
    CGFloat endA = startA + self.progress * M_PI_2 * 2.9;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    
    path.lineWidth = 5;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle= kCGLineJoinRound;
    [[UIColor colorWithRed:190/255.0 green:190/255.0 blue:200/255.0 alpha:1] set];
    [path stroke];
}
@end





